package com.gymmsystem.GYMMSystem.controller;

import com.gymmsystem.GYMMSystem.common.Result;
import com.gymmsystem.GYMMSystem.entity.Announcement;
import com.gymmsystem.GYMMSystem.service.AnnouncementService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;
    private static final Logger log = LoggerFactory.getLogger(AnnouncementController.class);
    /**
     * 获取已发布的公告
     */
    @GetMapping("/published")
    public ResponseEntity<Result<List<Announcement>>> getPublishedAnnouncements() {
        try {
            List<Announcement> announcements = announcementService.findAllAnnouncements();
            return ResponseEntity.ok(Result.success(announcements));
        }catch (Exception e){
            log.error("公告获取失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("公告获取失败"));
        }
    }

    /**
     * 获取所有公告
     */
    @GetMapping("/all")
    public Result<List<Announcement>> getAllAnnouncements() {

            List<Announcement> announcements = announcementService.selectAllAnnouncements();
            return Result.success(announcements);

    }
    /**
     * 根据ID获取公告详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Announcement>> getAnnouncementById(@PathVariable Long id) {
        try {
            Announcement announcement = announcementService.getAnnouncementById(id);
            if (announcement != null) {
                return ResponseEntity.ok(Result.success(announcement));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Result.error("公告不存在"));
            }
        } catch (Exception e) {
            log.error("获取公告详情失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取公告详情失败"));
        }
    }

    /**
     * 修改公告
     */
    @PutMapping("/update")
    public ResponseEntity<Result<Boolean>> updateAnnouncement(@RequestBody Announcement announcement) {
        try {
            boolean success = announcementService.updateAnnouncementById(announcement);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "公告更新成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("公告更新失败（可能ID不存在或内容为空）"));
            }
        } catch (Exception e) {
            log.error("更新公告失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("更新公告失败"));
        }
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<Boolean>> deleteAnnouncement(@PathVariable Long id) {
        try {
            boolean success = announcementService.deleteAnnouncementById(id);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "公告删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("公告删除失败"));
            }
        } catch (Exception e) {
            log.error("删除公告失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("删除公告失败"));
        }
    }

    /**
     * 创建新公告
     */
    @PostMapping("insert")
    public ResponseEntity<Result<Long>> createAnnouncement(@RequestBody Announcement announcement) {
        try {
            // 处理时间格式转换
            if (announcement.getScheduledPublishTime() != null) {
                // 确保时间格式正确，这里可以添加时间格式验证或转换逻辑
                // 由于前端已经发送ISO格式，后端可以直接使用
            }

            Long newId = announcementService.createAnnouncement(announcement);
            if (newId != null) {
                return ResponseEntity.ok(Result.success(newId, "公告创建成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("公告创建失败"));
            }
        } catch (Exception e) {
            log.error("创建公告失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("创建公告失败"));
        }
    }

    /**
     * 发布公告
     */
    @PutMapping("/{id}/publish")
    public ResponseEntity<Result<Boolean>> publishAnnouncement(@PathVariable Long id) {
        try {
            boolean success = announcementService.publishAnnouncement(id);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "公告发布成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("公告发布失败"));
            }
        } catch (Exception e) {
            log.error("发布公告失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("发布公告失败"));
        }
    }

    /**
     * 撤回公告
     */
    @PutMapping("/{id}/withdraw")
    public ResponseEntity<Result<Boolean>> withdrawAnnouncement(@PathVariable Long id) {
        try {
            boolean success = announcementService.withdrawAnnouncement(id);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "公告撤回成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("公告撤回失败"));
            }
        } catch (Exception e) {
            log.error("撤回公告失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("撤回公告失败"));
        }
    }
}

